package com.example.serviceb.controller;

import cn.hutool.core.util.IdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("good")
public class GoodController {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    StringRedisTemplate redisTemplate;

    @RequestMapping("/sell")
    public boolean sell() {


        // 判断是否满足条件
        String value = IdUtil.fastSimpleUUID();
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent("sell", value,
                300, TimeUnit.MILLISECONDS);

        // 查询数据库
        List<Map<String, Object>> maps = jdbcTemplate.queryForList("SELECT * FROM  `goods`");
        Map<String, Object> stringObjectMap = maps.get(0);
        Object goodsCount = stringObjectMap.get("goodsCount");
        Integer num = Integer.valueOf(goodsCount.toString());

        if (aBoolean) {
            if (num >= 1) {
                // 销售
                Integer integer = --num;
                System.out.println("售出了一个商品,剩余: " + integer);
                String update = "UPDATE\n" +
                        "  `db_goods`.`goods`\n" +
                        "SET\n" +
                        "  `goodsCount` = ? \n" +
                        "WHERE `gId` = ?";
                jdbcTemplate.update(update, new Object[]{integer, stringObjectMap.get("gId")});

                // 删除自己的锁
                if (redisTemplate.opsForValue().get("sell").equalsIgnoreCase(value)) {
                    redisTemplate.delete("sell");
                }
            }
        }
        // 返回结果
        return true;
    }

}
